package com.example.login.vm

import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.GsonUtils
import com.example.common.vm.BaseViewModel
import com.example.login.intent.LoginViewIntent
import com.example.login.model.LoginRepository
import com.example.login.state.LoginUiState
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody.Companion.toResponseBody

class LoginViewModel:BaseViewModel<LoginViewIntent>() {

    private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.NoneState)//内部使用的可变状态流
    val uiState:StateFlow<LoginUiState> = _uiState.asStateFlow()//对外提供的不可变转台流
    private var mRepository:LoginRepository = LoginRepository()

    override fun dispatchIntent(intent: LoginViewIntent) {
        when(intent){
            is LoginViewIntent.LoginToServer->loginToServer(intent.name,intent.pwd)
            is LoginViewIntent.RegisterToServer->registerToServer(intent.name,intent.pwd)
            else->{}
        }
    }



    //登录逻辑
    private fun loginToServer(name: String, pwd: String) {
        viewModelScope.launch(Dispatchers.IO) {

            try {
                //封装参数
                var mapParams = mutableMapOf("uName" to name,"uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis() / 1000).toString()
                var jsonParams = GsonUtils.toJson(mapParams)
                var paramsBody = jsonParams.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())

                //请求接口
                var resultData = mRepository.loginToServer(paramsBody)
                if(resultData.statuesCode =="200"){
                    //获取一下Token信息并保持
                    MMKV.defaultMMKV().encode("token",resultData.getValues().token)
                    MMKV.defaultMMKV().encode("home_url",resultData.home)
                    MMKV.defaultMMKV().encode("userId",resultData.getValues().uId)
                    //设置Flow数据,通知view层更新
                    _uiState.value = LoginUiState.LoginSuccess(resultData.getValues())
                }else{
                    _uiState.value = LoginUiState.LoginFail(resultData.msg)
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.value = LoginUiState.LoginFail(e.message?:"接口异常,请联系客服!!")
            }finally {
                cancel()//取消协程
            }
        }
    }
    //注册逻辑
    private fun registerToServer(name: String, pwd: String) {
        viewModelScope.launch(Dispatchers.IO){

            try {
                //封装参数
                var mapParams = mutableMapOf("uName" to name,"uPwd" to pwd)
                mapParams["time"] = (System.currentTimeMillis()/1000).toString()
                var jsonParams = GsonUtils.toJson(mapParams)
                var paramsBody = jsonParams.toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
                //请求接口
                var resultData = mRepository.registerToServer(paramsBody)
                if(resultData.statuesCode=="200"){
                    //设置Flow数据，通知view层更新
                    _uiState.value = LoginUiState.RegisterSuccess(resultData.getValues())
                }else{
                    _uiState.value = LoginUiState.RegisterFail(resultData.msg)
                }
            }catch (e:Exception){
                e.printStackTrace()
                _uiState.value = LoginUiState.RegisterFail(e.message?:"接口异常,请联系客服!!")
            }finally {
                cancel()//取消协程
            }


        }
    }


}